package main

import (
	"log"
	"os"
	"os/signal"
	"syscall"
	"testRabbitMq/rabbitmq"
	"time"
)

func main() {
	log.Println("start service")
	cfg := rabbitmq.DefaultMqConfig("test", 1001,
		"amqp://guest:guest@192.168.31.174:5020/test")
	mq := rabbitmq.NewRabbitMq(cfg, onMessage)
	mq.SubscribeTopic("testMq", false, false)
	mq.SubscribeTopic("testMq_autoAck", false, true)
	mq.Start()

	//createSender(mq, 4, 1, "testMq", "[testMq] hello!")
	//createSender(mq, 2, 1, "testMq_autoAck", "[testMq_Ack] hello!")

	s := make(chan os.Signal, 1)
	signal.Notify(s, syscall.SIGINT, syscall.SIGTERM)
	<-s
	log.Println("stop service")
	mq.Stop()
}

func onMessage(msg []byte, deliveryTag uint64, ack rabbitmq.AckLedger) {
	//log.Println("receive:", string(msg))
	err := ack.Ack(deliveryTag)
	if err != nil {
		log.Println(err)
	}
}

func createSender(mq rabbitmq.IRabbitMq, routineCount int, delayMillSec int, topic string, msgContent string) {
	f := func() {
		for true {
			mq.Publish(topic, []byte(msgContent))
			time.Sleep(time.Millisecond*time.Duration(delayMillSec))
		}
	}
	for i := 0; i < routineCount; i++ {
		go f()
	}
}